<template>
  <div class="message-view">
    <div class="messageContainer">
      <div class="message-left">
        <div>
          <h2 style="margin: 0;margin-bottom: 20px;font-size: 18px;font-weight: bolder">私信</h2>
        </div>
        <ul class="user-list">
          <li @click="handleUser(item)" style="display: flex;" v-for="(item, index) in messageStore.sessionList"
            :class="item.isActive ? 'active' : ''">
            <img style="width: 50px;height:50px;border-radius: 50%;margin-right: 20px" :src="item.displayAvatar" alt="">
            <div style="display: flex;align-items: flex-start;flex-direction: column;">
              <div style="display:flex;">
                <span style="font-size: 14px;margin-right: 10px;">{{ item.displayName }}</span>
                <span style="display: flex;align-items: center">
                  <span style="display: flex;align-items: center" v-if="item.online">
                    <div class="online"></div>在线
                  </span>
                  <span style="display: flex;align-items: center" v-else>
                    <div class="online" style="background-color: red"></div>离线
                  </span>

                </span>
              </div>
              <p class="lastMessage" style="margin-top: 10px">{{ item.lastMessage }}</p>
            </div>
          </li>
        </ul>
      </div>
      <div class="message-right">
        <div v-if="messageStore.sessionList.filter(item => item.isActive).length != 0"
          style="width: 100%;height: 100%;">
          <div style="display: flex;justify-content: space-between;align-items: center">
            <div style="font-size: 18px;font-weight: bolder">
              {{messageStore.sessionList.filter(item => item.isActive)[0] ? messageStore.sessionList.filter(item =>
                item.isActive)[0].displayName : ''}}
            </div>
            <span style="font-weight: bolder;font-size: 20px;cursor:pointer;">
              ···
            </span>
          </div>
          <t-divider />
          <div class="chatContent">
            <ul class="chat-list" ref="chatListRef">
              <li v-if="messageStore.chatList.length > 0" v-for="item in messageStore.chatList">
                <div :style="{
                  display: 'flex', flexDirection: item.role == 'user' ? 'row-reverse' : '',
                  alignItem: 'center'
                }">
                  <span style="margin:0 20px;font-size: 14px;color: white">{{ item.name }}</span>
                  <span style="transform: translateY(3px)">{{ item.datetime }}</span>
                </div>
                <div class="user1"
                  :style="{ display: 'flex', flexDirection: item.role == 'user' ? 'row-reverse' : '' }">
                  <img style="width: 50px;height: 50px;border-radius: 50%;margin: 10px 20px" :src="item.avatar" alt="">
                  <div
                    style="margin-top: 10px;display: flex;width:60%;align-items: center;justify-content: flex-end;max-width: 70%">
                    <p v-if="item.type == 1" class="contentMessage"
                      :style="{ justifyContent: item.role == 'user' ? 'flex-end' : 'flex-start' }">{{ item.content }}
                    </p>
                    <t-image-viewer v-if="item.type && item.type == '2'" :images="[item.content]">
                      <template #trigger="{ open }">
                        <div class="tdesign-demo-image-viewer__ui-image">
                          <img alt="test" :src="item.content" class="tdesign-demo-image-viewer__ui-image--img" />
                          <div style="margin-top: 20px;cursor:pointer;"
                            class="tdesign-demo-image-viewer__ui-image--hover" @click="open">
                            <span>
                              <BrowseIcon size="1.4em" /> 预览
                            </span>
                          </div>
                        </div>
                      </template>
                    </t-image-viewer>
                  </div>
                </div>

              </li>
              <BlurReveal v-else style="display: flex;justify-content: center;font-size: 17px">和TA打个招呼吧！👋</BlurReveal>
            </ul>
            <t-chat-input class="input" @send="inputEnter"> </t-chat-input>
          </div>
        </div>

        <div v-else style="position: absolute;left: 0;right: 0;top: 0;bottom: 0;">
          <AuroraBackground class="dark">
            <Motion as="div" :initial="{ opacity: 0, y: 40, filter: 'blur(10px)' }" :in-view="{
              opacity: 1,
              y: 0,
              filter: 'blur(0px)',
            }" :transition="{
              delay: 0.3,
              duration: 0.8,
              ease: 'easeInOut',
            }" class="relative flex flex-col items-center justify-center gap-4 px-4" style="color: white">

              <BlurReveal :duration="0.5" :delay="0.2" style="display: flex;flex-direction: column; justify-content: center;
                             align-items: center;position: relative;top: -100px">
                <p style="font-size: 30px;font-weight: bolder">你好，开始和你的朋友在Koala上畅聊吧！</p>
                <p style="font-size: 30px;font-weight: bolder">Hello, start chatting with your friends on Koala!</p>
              </BlurReveal>



            </Motion>
          </AuroraBackground>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { useUserStore } from "@/stores/modules/user.js";
const userStore = useUserStore()
import { BrowseIcon } from "tdesign-icons-vue-next";
const chatListRef = ref(null) // 获取 DOM 元素引用

// 滚动到底部的方法
// 修改后的滚动方法
const scrollToBottom = (behavior = 'smooth') => {
  nextTick(() => {
    if (!chatListRef.value) return;

    // 使用setTimeout确保所有DOM更新完成
    setTimeout(() => {
      const container = chatListRef.value;
      // 强制滚动到最大可能位置 + 额外100px
      const targetPos = container.scrollHeight + 100;

      container.scrollTo({
        top: targetPos,
        behavior
      });

      // 二次确认确保滚动到位（针对某些特殊浏览器）
      requestAnimationFrame(() => {
        if (container.scrollTop + container.clientHeight < container.scrollHeight) {
          container.scrollTop = container.scrollHeight;
        }
      });
    }, 50); // 适当延迟确保DOM更新
  });
}
// 这里将添加获取消息列表的逻辑
// 倒序渲染
import { nextTick, onMounted, ref } from "vue";
import { reqAddMessage, reqSessionMessageList, reqUserSessionList } from "@/api/user/message.js";
import { MessagePlugin } from "tdesign-vue-next";
import AuroraBackground from "@/components/ui/AuroraBackground.vue";
import Confetti from "@/components/ui/Confetti.vue";
import BlurReveal from "@/components/ui/BlurReveal.vue";
import { useRoute } from "vue-router";
import { useMessageStore } from "@/stores/modules/message.js";
import Notification from "@/components/ui/Notification.vue";
import NoticeList from "@/components/ui/NoticeList.vue";
const route = useRoute()
const sessionId = route.query.sessionId || '1911069514175430658'
const currentSessionId = ref('')
const messageStore = useMessageStore()

// 发送消息时
const inputEnter = (msg) => {

  const obj = {
    content: msg,
    sessionId: currentSessionId.value,
    type: 1
  }
  reqAddMessage(obj).then(res => {
    scrollToBottom()
  })
}

const sessionList = ref([])

const getMessageList = (sessionId) => {
  reqSessionMessageList(sessionId).then((res) => {
    messageStore.chatList = res.data
    messageStore.chatList.forEach((chat) => {
      if (chat.userId !== userStore.userId) {
        chat.role = 'assistant'
      } else {
        chat.name = '自己';
      }
    })
    scrollToBottom()
  })
}

// const chatList = ref([
//   {
//     avatar: userStore.avatar,
//     name: '自己',
//     datetime: '今天16:38',
//     content: '南极的自动提款机叫什么名字？',
//     role: 'user',
//     reasoning: '',
//   },
//   {
//     avatar: userStore.avatar,
//     name: '王某',
//     datetime: '今天16:38',
//     reasoning: '',
//     content: '它叫 McMurdo Station ATM，是美国富国银行安装在南极洲最大科学中心麦克默多站的一台自动提款机。在 JavaScript 中，HTML <video> 元素的 DOM 对象提供了一系列方法和属性来控制视频播放。以下是常见的 video DOM 对象方法及其用法说明',
//     role: 'assistant',
//     duration: 10,
//   },
//   {
//     avatar: userStore.avatar,
//     name: '王某',
//     datetime: '今天16:38',
//     reasoning: '',
//     content: userStore.avatar,
//     role: 'assistant',
//     duration: 10,
//     type:'1'
//   }
// ]);

// 点击切换用户时
const handleUser = (item) => {
  messageStore.sessionList.forEach((item2) => {
    item2.isActive = item2.sessionId == item.sessionId
  })
  currentSessionId.value = item.sessionId
  getMessageList(item.sessionId)
}


// 获取会话列表
const getSessionList = async () => {
  const res = await reqUserSessionList();
  if (res.code === 200) {
    messageStore.sessionList = res.data;
    if (sessionId) {
      messageStore.sessionList.forEach(item => {
        currentSessionId.value = sessionId
        item.isActive = item.sessionId === sessionId;
      })
      getMessageList(sessionId)
    }
  } else {
    MessagePlugin.error(res.message);
  }
}

onMounted(() => {
  getSessionList()
})

</script>

<style scoped>
.lastMessage {
  margin-top: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  /* 限制行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  /* 必须覆盖nowrap */
}

.contentMessage {
  font-size: 14px;
  position: relative;
  flex-wrap: wrap;
  top: -5px;
  width: 100%;
  display: flex;
}

.tdesign-demo-image-viewer__ui-image {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.user1 {}

.chat-list {
  height: 88%;
  overflow-y: auto;
  scroll-behavior: smooth;
  /* 可选：平滑滚动 */

}

.chat-list li {
  margin-bottom: 40px;
}

.input {}

.chatContent {
  height: 89%;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.online {
  margin-right: 5px;
  width: 12px;
  height: 12px;
  background-color: rgb(19, 193, 90);
  border-radius: 50%;

}

.user-list li {
  margin-bottom: 10px;
  cursor: pointer;
  padding: 20px;
  border-radius: 20px;
}

.user-list li:hover {
  background-color: rgb(53, 54, 65);
}

.active {
  background-color: rgb(53, 54, 65);
}

.user-list {
  overflow: auto;
  height: 90%;
  padding-right: 10px;
}

.message-left {
  flex: 3;
  box-sizing: border-box;
  padding: 20px;
  padding-right: 0px;
  height: 100%;
}

.message-right {
  flex: 10;
  border-left: 1px solid #4c4949;
  padding: 20px;
  box-sizing: border-box;
  position: relative;

}

.message-view {
  color: #c0c0d6;
  display: flex;
  height: 100%;
  width: 100%;
  align-items: center;
  justify-content: center;
}

.messageContainer {
  display: flex;
  background-color: rgb(37, 38, 50);
  height: 100%;
  width: 95%;
  border-radius: 20px;
}
</style>
